<?php
// OpenAI API 密钥
//$apiKey = 'sk-oy5ec_AT27C6si9UY22Uwn86iNadMdoNeOMDedEDpgT3BlbkFJTwUxVe3hrCl9QnlzEHfVbEmiAGIvLkVzU2c3Yg2IgA';
$apiKey = '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';

// API 请求 URL
$url = 'https://api.openai.com/v1/chat/completions';

// 请求数据
$data = [
    'model' => 'gpt-3.5-turbo',  // 或 'gpt-4'
    'messages' => [
        ['role' => 'system', 'content' => 'You are a helpful assistant.'],
        ['role' => 'user', 'content' => '你好，今天天气怎么样？']
    ],
    'temperature' => 0.7,
];

// 初始化 cURL
$ch = curl_init($url);

// 设置 cURL 选项
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Authorization: Bearer ' . $apiKey,
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));

// 执行请求并获取响应
$response = curl_exec($ch);

// 检查是否有错误
if (curl_errno($ch)) {
    echo 'Request Error: ' . curl_error($ch);
} else {
    // 解析并输出响应结果
    $responseData = json_decode($response, true);

    var_dump($response);
    $message = $responseData['choices'][0]['message']['content'] ?? 'No response';
    echo "ChatGPT: " . $message;
}

// 关闭 cURL
curl_close($ch);
?>